package com.qs.home.ui.activity;

import android.databinding.Observable;
import android.os.Bundle;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.ocr.demo.FileUtil;
import com.baidu.ocr.demo.RecognizeService;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.qs.base.base.BaseMyActivity;
import com.qs.base.router.RouterActivityPath;
import com.qs.home.BR;
import com.qs.home.R;
import com.qs.home.databinding.HomeIdCardActivityBinding;
import com.qs.home.ui.VM.IdCardViewModel;

import java.io.File;

import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * 身份证识别
 *
 * @Author ltzz
 * @Date 2019/8/13
 */
@Route(path = RouterActivityPath.Home.ID_CARD)
public class IdCardActivity extends BaseMyActivity<HomeIdCardActivityBinding, IdCardViewModel> {
    @Override
    protected boolean statusBarDarkFont() {
        return true;
    }

    @Override
    protected View titleLayout() {
        return null;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.home_id_card_activity;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.head.setTitleLeftText("身份证识别");
        binding.head.setAutoFinish(this);

        //  初始化本地质量控制模型,释放代码在onDestory中
        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
        CameraNativeHelper.init(this, OCR.getInstance(this).getLicense(),
                new CameraNativeHelper.CameraNativeInitCallback() {
                    @Override
                    public void onError(int errorCode, Throwable e) {
                        String msg;
                        switch (errorCode) {
                            case CameraView.NATIVE_SOLOAD_FAIL:
                                msg = "加载so失败，请确保apk中存在ui部分的so";
                                break;
                            case CameraView.NATIVE_AUTH_FAIL:
                                msg = "授权本地质量控制token获取失败";
                                break;
                            case CameraView.NATIVE_INIT_FAIL:
                                msg = "本地质量控制";
                                break;
                            default:
                                msg = String.valueOf(errorCode);
                        }
                        ToastUtils.showLong("本地质量控制初始化错误，错误原因： " + msg);
                    }
                });
    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //图片识别
        viewModel.uc.photoDiscernUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (StringUtils.isTrimEmpty(viewModel.uc.photoDiscernUc.get()))
                    return;
                if (StringUtils.equals(viewModel.uc.photoDiscernUc.get(), "front")) {
                    String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                    recIDCard(viewModel.uc.photoDiscernUc.get(), filePath);
                }
                viewModel.uc.photoDiscernUc.set("");
            }
        });
    }

    /**
     * 身份证识别
     *
     * @param idCardSide
     * @param filePath
     */
    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        viewModel.showDialog();
        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                viewModel.dismissDialog();
                if (result != null) {
                    KLog.e(result.toString());
                    ARouter.getInstance().build(RouterActivityPath.Home.ID_CARD_IDENTIFY_RESULTS_ACTIVITY).withString("textResult", result.toString()).navigation();
                }
            }

            @Override
            public void onError(OCRError error) {
                viewModel.dismissDialog();
                KLog.e(error);
            }
        });
    }
}
